<template>
    <div class="userInfoContainer">
        <el-form ref="form" :model="userFrom" label-width="80px">
            <el-form-item label="用户头像">
                <img class="avatar" :src="userFrom.avatar">
                <br>更改头像
                <input type="file" @input="upFile($event)">
            </el-form-item>

            <el-form-item label="用户名">
            <el-input v-model="userFrom.name"></el-input>
            </el-form-item>

            <el-form-item label="密码">
                <el-input v-model="userFrom.password"></el-input>
            </el-form-item>

            <el-form-item label="权限">
            <el-select v-model="userFrom.role" placeholder="请选择">
                <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addAndUpdate">{{operation}}</el-button>
                <el-button @click="reset">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import{selectUserById,addUser,updateUser} from '@/api/user'
import fileStore  from '@/api/fileStore';
import { getToken } from '@/utils/auth';
export default {
    data(){
        return {
            id:null,
            userFrom:{
                id:'',
                name:'',
                password:'',
                avatar:'',
                role:''
            },
            roleOptions:[
                {
                    label:"管理员",
                    value:"100000_1000001_1000002"
                },
                {
                    label:"普通用户",
                    value:"1000001_1000002"
                },
                {
                    label:"访客",
                    value:"1000002"
                }
            ],
            operation:''
        }
    },
    created() {
      //初始化 
      this.init()
    },
    watch:{ //当页面路由发生变化时就会执行
      $route(to,from) {
          this.init();
      }
    },
    methods: {
      //初始化用户
      init() {
          //当前页面是否携带id,带id查询出值
          if(this.$route.params && this.$route.params.id) {
              this.id  = this.$route.params.id;
              this.userFrom.id = this.id;
              this.operation="修改"
              this.getUser();
          } else { //路径没有id值
              //清空表单
              this.operation="创建"
              this.reset()
          }
      },
      //获取用户
      getUser(){
        selectUserById(this.userFrom.id)
            .then(response=>{
                this.userFrom = response.data.user;
                var code = response.data.user.role;
                var codeArr = code.split("_");
                // if(codeArr[0] == "100000"){
                //     userFrom.role = '管理员'
                // }
                // if(codeArr[0] == "1000001"){
                //     userFrom.role = '普通用户'
                // }
                // if(codeArr[0] == "1000002"){
                //     userFrom.role = '访客'
                // }
            })
      },
      //修改和添加用户
      addAndUpdate(){
        if(!this.checkForm()){
            return;
        }
        if(this.userFrom.id){
            //修改
            updateUser(this.userFrom)
                .then(response=>{
                    if(response.data.update){
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    }
                    this.reset();
                })
        }else{
            //增加
            addUser(this.userFrom)
                .then(response=>{
                    if(response.data.add){
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                    }
                    this.reset();
                })
        }
      },
      //上传文件检查
      checkFile(file) {
        var reg = new RegExp(".*\\.(jpg|jpeg|png|gif|bmp|svg)$");
        const isJPG = reg.test(file.name);
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/png/gif 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return isJPG && isLt2M;
      },
      //检查数据
      checkForm(){
        if(this.userFrom.name.length >= 6 && this.userFrom.password.length >=6){
            return true;
        }
        this.$message('用户名和密码最少6位!');
        return false;
      },
      //加载文件
      loadFile(file){
        return new Promise((success)=>{
            //读取文件流
            var reader = new FileReader();
            var binData=null;
            let data = reader.readAsArrayBuffer(file);
            reader.addEventListener('load',(e=>{
                binData = new Blob([e.target.result],{type:file.type});
                success(binData);
            }));
        })
      },
      //上传文件
      async upFile(event){
        var file = event.target.files[0];
        if(!this.checkFile(file)){
            return;
        }
        var binData = await this.loadFile(file);
        //封装文件
        var upload = new FormData();
        //参数名 文件 文件名
        upload.append('file',binData,file.name);
        fileStore.upLoadFile(upload)
            .then(response=>{
                //上传文件后检查头像是否已经存在
                if(this.userFrom.avatar == response.data.file.url){
                    this.$message.success('更换成功');
                    return;
                }
                if(this.userFrom.avatar.length>1){
                    fileStore.deleteFile(this.userFrom.avatar)
                        .then(response=>{
                            this.$message.success('更换成功');
                        })
                }
                this.userFrom.avatar = response.data.file.url;
            })
      },
      //重置条件
      reset(){
        this.userFrom.name='';
        this.userFrom.avatar='';
        this.userFrom.password='';
        this.userFrom.role='';
        this.userFrom.id = this.id;
      }
    }
}
</script>
<style>
.userInfoContainer {
    margin-top: 10%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>